<?php

namespace app\api\controller;

use app\api\model\Third;
use app\api\model\User;
use app\common\trilateral\wxBizDataCrypt;
use app\common\controller\Api;

class Login extends Api
{

    protected $noNeedLogin = ['Login','curl_get'];
    protected $noNeedRight = ['*'];

    /**
     * 登录
     * @return void
     * @throws \think\exception\DbException
     */
    public function Login(){
        $param = request()->param();
        $code=$param['code'];
        $appid = $this->config_data('appid');//小程序的appid
        $appSecret = $this->config_data('secret');// 小程序的$appSecret
        $wxUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
        $getUrl = sprintf($wxUrl, $appid, $appSecret, $code);//把appid，appsecret，code拼接到url里
        $result = self::curl_get($getUrl);//请求拼接好的url
        $wxResult = json_decode($result, true);
//        $wxResult=$param;
        if (empty($wxResult)) {
            $this->error('获取openid时异常，微信内部错误');
        }else{
            if(!empty($wxResult['errcode'])){
                $this->error($wxResult['errmsg']);
            }
            $openid = $wxResult['openid'];
            $where_third['openid']=$openid;
            $Third = new Third();
            $User = new User();
            $Third_find= $Third->get($where_third);
            if(empty($Third_find)){
                $User->nickname=$this->config_data('nickname')."_".rand(1111,9999);
                $User->avatar=$this->config_data('avatar');
                $User->jointime=time();
                $User->status="normal";
                $User->pid=$param['pid'];
                $User->save();
                $Third->user_id=$User->id;
                $Third->platform="微信";
                $Third->apptype="小程序";
                $Third->openid=$openid;
                $Third->save();
                $data['is_mobile']=0;
                $data['improve']=0;
                $this->auth->direct($User->id);

                if(!empty($param['pid'])){
                    $this->user_money($param['pid'],$this->config_data('share'),1,"分享获得钢豆");
                    $User->where(['id'=>$param['pid']])->setInc('share_num',1);
                }
            }else{
                $this->auth->direct($Third_find['user_id']);
                $user_find=$User->get($Third_find['user_id']);
                if(empty($user_find['mobile'])){
                    $is_mobile=0;
                }else{
                    $is_mobile=1;
                }
                $data['is_mobile']=$is_mobile;
                $data['improve']=$user_find['improve'];
            }
            $data['sessionKey']=$wxResult['session_key'];
            $data['token']=$this->auth->getToken();
            $data['openid']=$openid;
            $this->success('成功',$data);
        }
    }

    /**
     * 获取手机号
     * @return void
     */
    public function getPhone(){
        $param = request()->param();
        $user=$this->auth;
        $UserM = new User();
        $appid 			= $this->config_data('appid');//小程序的appid
        $sessionKey 	= $param['sessionKey'];//小程序传传过来的session_key
        $encryptedData  = $param['encryptedData'];//小程序传传过来的encryptedData
        $iv 			= $param['iv'];//小程序传传过来的iv
        if (empty($sessionKey)){
            $this->error('sessionKey不能为空');
        }
        if (empty($encryptedData)){
            $this->error('encryptedData不能为空');
        }
        if (empty($iv)){
            $this->error('iv不能为空');
        }
        $wx = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $wx->decryptData($encryptedData, $iv, $datase);
        if($errCode == 0){
            $data = json_decode($datase,true);
            $updata_user['mobile'] = $data['phoneNumber'];
            $where['id']=$user->id;
            $UserM->save($updata_user,$where);
            $this->success('绑定成功',$data);
        }else{
            $this->error('sessionKey过期请重新授权登录');
        }


    }

    /**
     * curl
     * @param $url
     * @param $httpCode
     * @return bool|string
     */
    public function curl_get($url, &$httpCode = 0) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //不做证书校验,部署在linux环境下请改为true
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $file_contents = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $file_contents;
    }
}
